import  numpy  as  np
import  cv2
import sys
import matplotlib.pyplot as plt

cap = cv2.VideoCapture('video/VID_20180207_171111.mp4')
list = []
i=1
j=1
list1=[]

while (cap.isOpened()):
    black = 0
    white = 0

    ret,frame = cap.read()
    if ret == False :
        break

    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    if i == 1 :
        height , width =frame.shape[:2]

        color = np.uint8([[frame[int(height/2),150]]])

        hsv_green = cv2.cvtColor(color, cv2.COLOR_BGR2HSV)

        hue = hsv_green[0][0][0]


    if i%5 != 0:
        #每5帧取一次    手机摄像头为30fps  这里保证6HZ的频率取点  可以保证180/min 的心跳 满足检测要求
        #也就是每个样本点 间隔 1/6 秒   这样也避免了样本过多 导致的误差
        i+=1
        continue
    #设置阈值
    lower_red = np.array([hue-5,100,100])
    upper_red = np.array([hue-1,255,255])

    mask = cv2.inRange(hsv,lower_red,upper_red)

    dst = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.namedWindow('dst',cv2.WINDOW_NORMAL)
    cv2.imshow("dst", dst)

    #每 50*50的像素空间取一个点  节省效率   1980*1080 为例  50*50空间样本800个   10*10空间样本2W+ 1*1空间（大概率跑死）  213W+   图像几乎不会导致误差
    for h in range(0,height,50):
        for w in range(0,width,50):
            if mask[h,w] == 255:
                black+=1
            else:
                white+=1

    #记录黑色点所占空间   按照观察经验  当黑色拓张时 为脉搏（当然也需要考虑 mask取法）
    list.append( (white/ (black+white) )*100 )
    list1.append( {'no':i,'area':(white/ (black+white) )*100} )
    dt = 1
    t = np.arange(0, j, dt)
    nse = list
    r = np.exp(0 / 100)


    i+=1
    j+=1
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
         break


cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse

plt.plot(t, s)
plt.show()

cv2.destroyAllWindows()
cap.release()

